package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeMapper employeeMapper;

	/**
	 * 员工登录
	 *
	 * @param employeeLoginDTO
	 * @return
	 */
	@Override
	public Employee login(EmployeeLoginDTO employeeLoginDTO) {
		String username = employeeLoginDTO.getUsername();
		String password = employeeLoginDTO.getPassword();

		//1、根据用户名查询数据库中的数据
		Employee employee = employeeMapper.getByUsername(username);

		//2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
		if (employee == null) {
			//账号不存在
			throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
		}

		//密码比对
		//对前端的明文密码进行md5加盐加密处理
		password = DigestUtils.md5DigestAsHex((password + PasswordConstant.PASSWORD_SALT).getBytes());
		if (!password.equals(employee.getPassword())) {
			//密码错误
			throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
		}

		if (StatusConstant.DISABLE.equals(employee.getStatus())) {
			//账号被锁定
			throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
		}

		//3、返回实体对象
		return employee;
	}

	/**
	 * 新增员工
	 *
	 * @param employeeDTO
	 */
	@Override
	public void save(EmployeeDTO employeeDTO) {

		//根据用户名查数据库中是否已存在，存在则抛出异常
		if (employeeMapper.getByUsername(employeeDTO.getUsername()) != null) {
			//账号已存在
			throw new InsertionNotAllowedException(MessageConstant.ACCOUNT_ALREADY_EXISTS);
		}
		//对象属性拷贝
		Employee employee = new Employee();
		BeanUtils.copyProperties(employeeDTO, employee);
		//修改员工状态，1表示正常，0表示锁定
		employee.setStatus(StatusConstant.ENABLE);
		//设置密码，默认密码为123456
		employee.setPassword(DigestUtils.md5DigestAsHex((PasswordConstant.DEFAULT_PASSWORD + PasswordConstant.PASSWORD_SALT).getBytes()));

		employeeMapper.insert(employee);
	}

	/**
	 * 员工分页查询
	 *
	 * @param employeePageQueryDTO
	 * @return
	 */
	@Override
	public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
		//开始分页查询
		PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

		Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

		return new PageResult(page.getTotal(), page.getResult());
	}

	/**
	 * 启用禁用员工账号
	 *
	 * @param status
	 * @param id
	 */
	@Override
	public void startOrStop(Integer status, Long id) {
		Employee employee = Employee.builder().id(id).status(status).build();
		employeeMapper.update(employee);
	}

	/**
	 * 根据id查询员工信息
	 *
	 * @param id
	 * @return
	 */
	@Override
	public Employee getById(Long id) {
		return employeeMapper.getById(id);
	}

	/**
	 * 修改员工信息
	 *
	 * @param employeeDTO
	 */
	@Override
	public void update(EmployeeDTO employeeDTO) {
		//如果修改了员工用户名
		if (!employeeMapper.getById(employeeDTO.getId()).getUsername().equals(employeeDTO.getUsername())) {
			//如果修改后的用户名是已经存在的
			if (employeeMapper.getByUsername(employeeDTO.getUsername()) != null) {
				//抛出异常账号已存在
				throw new UpdateNotAllowedException(MessageConstant.ACCOUNT_ALREADY_EXISTS);
			}
		}
		Employee employee = new Employee();
		BeanUtils.copyProperties(employeeDTO, employee);

		employeeMapper.update(employee);
	}

	/**
	 * 修改密码
	 *
	 * @param passwordEditDTO
	 */
	@Override
	public void editPassword(PasswordEditDTO passwordEditDTO) {
		//判断传入的新密码是否为空
		if (!StringUtils.hasText(passwordEditDTO.getNewPassword()) || !StringUtils.hasText(passwordEditDTO.getOldPassword())) {
			throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
		}
		//根据id查询员工数据
		Employee employee = employeeMapper.getById(passwordEditDTO.getEmpId());
		//判断传入的旧密码是否和数据库中的一致
		String oldPassword = DigestUtils.md5DigestAsHex((passwordEditDTO.getOldPassword() + PasswordConstant.PASSWORD_SALT).getBytes());
		if (!employee.getPassword().equals(oldPassword)) {
			throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
		}
		//判断新旧密码是否一致
		String newPassword = DigestUtils.md5DigestAsHex((passwordEditDTO.getNewPassword() + PasswordConstant.PASSWORD_SALT).getBytes());
		if(employee.getPassword().equals(newPassword)){
			throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
		}
		//修改数据库中该员工的密码
		employee.setPassword(newPassword);
		employeeMapper.update(employee);
	}
}
